from utils.my_drf.viewsets import CustomTreeModelViewSet
from rest_framework.viewsets import GenericViewSet
from utils.my_drf.response import APIResponse
from django.conf import settings
from django.core.cache import cache
from . import serializer, models
from utils.my_drf.admin_auth import AdminJwtAuth, AdminPermission
from record.models import AdminRecord


# 获取管理员菜单权限
class GetAdminMenuView(GenericViewSet):
    authentication_classes = [AdminJwtAuth, ]

    queryset = models.Menu.objects.filter(is_delete=False).order_by('-ord', '-id')
    serializer_class = serializer.MenuSerializer

    def list(self, request):
        # 获取用户权限
        user_auth = request.user.get('role')
        # 获取所有菜单
        menu_all = cache.get('admin_menu_all')
        if not menu_all:
            ser = self.get_serializer(instance=self.get_queryset(), many=True)
            menu_all = ser.data
            cache.set('admin_menu_all', menu_all, settings.ZEUS_CACHES_TIME)
        # 循环菜单 组成新的菜单
        menu_list_all = []
        for item in menu_all:
            temp_item = {}
            # 如果是超级管理员，添加上所有权限
            if request.user.get('is_superuser') and str(item['id']) not in user_auth:
                user_auth.append(str(item['id']))
            # 如果是路由并且在权限里
            if item['is_route'] and str(item['id']) in user_auth:
                temp_item['path'] = item['path']
                temp_item['name'] = item['name']
                temp_item['component'] = item['component']
                temp_item['meta'] = {
                    'id': item['id'],
                    'title': item['title'],
                    'icon': item['icon'],
                    'pid': item['pid'],
                    'is_menu': item['is_menu']
                }
                menu_list_all.append(temp_item)
        menu_list = self._get_menu_list(menu_list_all)
        return APIResponse(data={'auth': user_auth, 'menu_list': menu_list})

    # 利用浅拷贝生成树形菜单
    def _get_menu_list(self, menu_data):
        for index, i in enumerate(menu_data):
            for j in menu_data:
                if i['meta']["id"] == j['meta']["pid"]:
                    if "children" not in menu_data[index].keys():
                        menu_data[index]["children"] = []
                    menu_data[index]["children"].append(j)
        res = [item for item in menu_data if not item['meta']["pid"]]
        return res


# 菜单
class AdminMenuView(CustomTreeModelViewSet):
    authentication_classes = [AdminJwtAuth, ]
    permission_classes = [AdminPermission, ]

    queryset = models.Menu.objects.filter(is_delete=False).order_by('-ord', '-id')
    serializer_class = serializer.MenuSerializer

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        AdminRecord.objects.create(group=1, detail='添加菜单，内容：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        cache.delete('admin_menu_all')
        return res

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        AdminRecord.objects.create(group=1, detail='修改菜单，内容：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        cache.delete('admin_menu_all')
        return res

    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        AdminRecord.objects.create(group=1, detail='删除菜单，id：{}'.format(str(res.data.get('data'))),
                                   admin_id=request.user.get('id'))
        cache.delete('admin_menu_all')
        return res
